from django.shortcuts import render, render_to_response
from .models import Lingo
from django.http import HttpResponseRedirect
from django.urls import reverse


def login_view(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = Lingo.objects.get(username__exact=username)
        if user.password == password:
            response = HttpResponseRedirect(reverse('campaign_for:select'))
            # 添加cookie
            response.set_cookie('username', username.encode('utf-8').decode('iso-8859-1'))
            # 获取COOKIES值
            # "username": request.COOKIES['username'],
            return response
        else:
            return render(request, 'login.html', {'error_message': '姓名或学号错误，如姓名或学号无错误请反馈部长'})
    else:
        return render(request, 'login.html')


def logout_view(request):
    if request.method == 'GET':
        response = HttpResponseRedirect(reverse('campaign_for:select'))
        response.delete_cookie('username')
        return response


def page_not_found(request, **kwargs):
    # 全局404处理函数
    response = render_to_response('404.html', {})
    response.status_code = 404
    return response
